#include "util/StringUtils.h"
#include <sstream>

namespace util {

void trim(std::string& str) {
	std::string::size_type pos = str.find_last_not_of(' ');
	if (pos != std::string::npos) {
		str.erase(pos + 1);
		pos = str.find_first_not_of(' ');
		if (pos != std::string::npos) {
			str.erase(0, pos);
		}
	} else {
		str.erase(str.begin(), str.end());
	}
}

double stringToDouble(std::string str) throw (parser::InvalidDataException) {
	std::istringstream isstream(str); // convierte el string en un input stream
	double dvalue = 0.0;
	// intenta guardar el string en un double. Si se pudo, devuelve el valor.
	if (isstream >> dvalue) {
		return dvalue;
	} else {
		throw(parser::InvalidDataException("No se pudo convertir \"" + str
				+ "\" en un double."));
	}
}

std::string intToString(int i) {
	char* aux = new char[5];
	sprintf(aux, "%i", i);
	std::string ret(aux);
	delete aux;
	return ret;
}

std::string doubleToString(double d) {
	char* aux = new char[20];
	sprintf(aux, "%f", d);
	std::string ret(aux);
	delete aux;
	return ret;
}

}
